﻿namespace LocalTest.Web.Middleware;

public class AuthUserMiddleware : IMiddleware
{
    private int _count = 0;

    public Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        // var values = context.Request.Headers["Token"];
        // if (values.Count == 0)
        // {
        //     throw new UnauthorizedAccessException("token 过期");
        // }
        //
        // context.Items["Token"] = values[0];

        _count++;
        Console.WriteLine(
            $"AuthUserMiddleware-Request:{Thread.CurrentThread.Name}-{Thread.CurrentThread.ManagedThreadId}-count:{_count}");
        context.Response.OnCompleted(() =>
        {
            context.Items.Remove("Token");
            Console.WriteLine(
                $"AuthUserMiddleware-Response:{Thread.CurrentThread.Name}-${Thread.CurrentThread.ManagedThreadId}-count:{_count}");
            return Task.CompletedTask;
        });
        return next(context);
    }
}

public static class AuthUserMiddlewareExtensions
{
    public static IServiceCollection UseAuthUserMiddlewareService(this WebApplicationBuilder builder)
    {
        return builder.Services.AddScoped<AuthUserMiddleware>();
    }

    public static IApplicationBuilder UseAuthUserMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<AuthUserMiddleware>();
    }
}